package com.gitee.wsl.coroutines.sequences

import com.gitee.wsl.coroutines.collections.sequences.suspendingSequence
import com.gitee.wsl.platform.concurrent.runBlocking
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlin.random.Random
import kotlin.test.Test


class SuspendingSequenceTest {
    @Test
    fun suspendingSequenceTest(){
        runBlocking {
            // asynchronously generate a number every 500 ms
            val seq = suspendingSequence {
                log("Starting generator")
                for (i in 1..10) {
                    log("Generator yields $i")
                    yield(i)
                    val generatorSleep = 500L
                    log("Generator goes to sleep for $generatorSleep ms")
                    delay(generatorSleep)
                }
                log("Generator is done")
            }

            // consume asynchronous sequence with a regular for loop
            for (value in seq) {
                log("Consumer got value = $value")
                val consumerSleep = Random.nextInt(1000).toLong()
                log("Consumer goes to sleep for $consumerSleep ms")
                delay(consumerSleep)
            }
        }
    }

    fun log(test:String){
        println(test)
    }
}